package com.ygqh.baby.controller;

import com.ygqh.baby.ao.*;
import com.ygqh.baby.po.YgOrder;
import com.ygqh.baby.po.YgProduct;
import com.ygqh.baby.service.YgOrderService;
import com.ygqh.baby.service.YgProductService;
import com.ygqh.baby.service.erp.ErpApi;
import com.ygqh.baby.utils.DateConvertUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/basicData")
public class ErpController {
	protected final Logger logger = Logger.getLogger(this.getClass());
	@Autowired
	private YgOrderService ygOrderService;
	@Autowired
	private YgProductService ygProductService;
	@Autowired
	private ErpApi erpApi;

	@RequestMapping("/syncOrderToErp")
	@ResponseBody
	public void syncOrderToErp() {
		Date endDate = new Date();
		Date startDate = DateConvertUtils.addMinute(endDate, -100);
		List<YgOrder> orderList = ygOrderService.findByPaidTimeHasDetail(startDate, endDate, null, OrderStatus.WaitingCheck, OrderStatus.WaitingSend);

		if (CollectionUtils.isEmpty(orderList)) {
			return;
		}
		erpApi.orderPush(orderList);

	}

	@RequestMapping("/productPush")
	@ResponseBody
	public void productPush() {
		String[] skuCodes = new String[]{};
		List<YgProduct> pList = ygProductService.findBySkuCodes(PromotionType.Ordinary, skuCodes);
		erpApi.productPush(pList);
	}

	@RequestMapping("/getProduct")
	@ResponseBody
	public Message getProduct(String[] skuCodes) {
		List<YgProduct> pList = ygProductService.findBySkuCodes(PromotionType.Ordinary, skuCodes);
		Map<String, Object> map = new HashMap<>();
		map.put("productList", pList);
		map.put("totalCount", pList.size());
		return Message.success(map);
	}

	@RequestMapping("/getYiigooProductByTime")
	@ResponseBody
	public Message getProduct(QueryInfo queryInfo, String startTime, String endTime, PromotionType promotionType, ProductStatus productStatus) {
		if (promotionType == null) {
			promotionType = PromotionType.Ordinary;
		}
		Date startDate = DateConvertUtils.parse(startTime, DateConvertUtils.DATE_TIME_FORMAT);
		Date endDate = DateConvertUtils.parse(endTime, DateConvertUtils.DATE_TIME_FORMAT);
		List<YgProduct> pList = ygProductService.findProductByTime(queryInfo, startDate, endDate, promotionType, productStatus);
		int totalCount = ygProductService.countProductByTime(startDate, endDate, promotionType, productStatus);
		Map<String, Object> map = new HashMap<>();
		map.put("productList", pList);
		map.put("totalCount", totalCount);
		return Message.success(map);
	}
}
